package org.kjtc.balanceController;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.kjtc.balanceEntity.BalanceBill;
import org.kjtc.balanceEntity.ChargingRecord;
import org.kjtc.balanceEntity.LineBalance;
import org.kjtc.balanceEntity.ReviewRecord;
import org.kjtc.balanceEntity.SubBranchCompanyBalance;
import org.kjtc.balanceEntity.SummaryBalance;
import org.kjtc.balanceService.BalanceService;
import org.kjtc.balanceService.CostManageService;
import org.kjtc.controller.BaseController;
import org.kjtc.exportService.ExportAllLineBalance;
import org.kjtc.exportService.ExportCostBalanceBill;
import org.kjtc.exportService.ExportLineBalance;
import org.kjtc.exportService.ExportPhaseSummary;
import org.kjtc.exportService.ExportStageSummary;
import org.kjtc.exportService.ExportSubBranchCompanyBalance;
import org.kjtc.exportService.ExportSummaryBalance;
import org.kjtc.util.DoubleUtil;
import org.kjtc.util.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BalanceExportController extends BaseController {

	@Resource(name = "costManageService")
	private CostManageService costManageService;
	
	@Resource(name = "balanceService")
	private BalanceService balanceService;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportSummaryBalance")
	@ResponseBody
	public Map<String, Object> exportSummaryBalance(String checkFlag, String exportFlag, Integer balanceDay, HttpServletResponse response){

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "结算报表导出");

		if (!checkFlag.isEmpty()) {
			if ("1".equals(exportFlag)) {
				List<SummaryBalance> list = (List<SummaryBalance>) this.getSession().getAttribute("summaryBalanceList");
				ExportSummaryBalance<SummaryBalance> summaryBalance = new ExportSummaryBalance<SummaryBalance>();
				String[] headers = {"序号", "充电日期", "充电站名称", "分公司\r\n名称", "充电次数\r\n(总)/次", "充电电量\r\n(总)/度", "贸易表电量\r\n(总)/千瓦时", "电费\r\n(总)/元", "充电服务费\r\n(总)/元", "总费用/元"};
				String summaryBalanceListTitle = this.getSession().getAttribute("summaryBalanceListTitle").toString();
				String title = summaryBalanceListTitle.substring(0, 4) + "年" + summaryBalanceListTitle.substring(4, 6).concat("月结算汇总表");
				Date startDTTM = list.get(0).getStartChargingDTTM();
				Date endDTTM = list.get(0).getEndChargingDTTM();
				for (int i = 1; i < list.size(); i++) {
					if (list.get(i).getStartChargingDTTM().getTime() < startDTTM.getTime()) {
						startDTTM = list.get(i).getStartChargingDTTM();
					}
					if (list.get(i).getEndChargingDTTM().getTime() > endDTTM.getTime()) {
						endDTTM = list.get(i).getEndChargingDTTM();
					}
				}
				for (int i = 0; i < list.size(); i++) {
					list.get(i).setEffectiveDTTM(Tools.date2Str(startDTTM, "yyyy年MM月dd日").concat("至").concat(Tools.date2Str(endDTTM,"yyyy年MM月dd日")));
				}
				try {
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/x-download");
					String filedisplay = title.concat(".xls");
					filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
					response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
					summaryBalance.exportExcel(title, headers, list, response.getOutputStream(), null);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if ("2".equals(exportFlag)) {
				List<SubBranchCompanyBalance> list = (List<SubBranchCompanyBalance>) this.getSession().getAttribute("subBranchCompanyBalanceList");
				ExportSubBranchCompanyBalance<SubBranchCompanyBalance> subBranchCompanyBalance = new ExportSubBranchCompanyBalance<SubBranchCompanyBalance>();
				String[] headers = {"序号", "日期", "充电站", "车队", "线路", "92号汽油当日油价/升", "充电电量/度", "系数", "结算电量/度", "电费单价", "电费小计", "提取服务标准", "服务费小计", "费用合计"};
				String title = this.getSession().getAttribute("subBranchCompanyBalanceListTitle").toString();
				try {
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/x-download");
					String filedisplay = title.concat(".xls");
					filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
					response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
					subBranchCompanyBalance.exportExcel(title, headers, list, response.getOutputStream());
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if ("3".equals(exportFlag)) {
				List<LineBalance> list = (List<LineBalance>) this.getSession().getAttribute("lineBalanceList");
				ExportLineBalance<LineBalance> lineBalance = new ExportLineBalance<LineBalance>();
				String title = this.getSession().getAttribute("lineBalanceListTitle").toString();
				String[] headers = {"序号", "日期", "充电站", "车队", "线路", "充电电量/度", "系数", "结算电量/度", "电费单价", "电费小计", "92号汽油当日油价/升", "提取服务费标准", "服务费小计", "费用合计"};
				try {
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/x-download");
					String filedisplay = title.concat(".xls");
					filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
					response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
					lineBalance.exportExcel(headers, list, response.getOutputStream());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			map.put("result", "Success");
		}

		return map;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportCostBalanceBill")
	@ResponseBody
	public Map<String, Object> exportCostBalanceBill(String checkFlag, HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "电力对比导出");

		if (!checkFlag.isEmpty()) {
			String[] headers = {"序号", "充电站名称", "上次抄表时间", "本次抄表时间", "电表表号", "电表倍率", "上次抄表(总)", "上次抄表(尖)", "上次抄表(峰)", "上次抄表(平)", "上次抄表(谷)", "上次抄表(无功)", "本次抄表(总)", "本次抄表(尖)", "本次抄表(峰)", "本次抄表(平)", "本次抄表(谷)", "本次抄表(无功)", "有功总电量", "有功尖电量", "有功峰电量", "有功平电量", "有功谷电量", "尖时占比", "峰时占比", "平时占比", "谷时占比", "实际缴纳电费", "实际充电量", "电量系数", "结算电费", "电费差值", "比值"};
			List<BalanceBill> list = (List<BalanceBill>) this.getSessionAttribute("costBalanceBillList");
			try {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/x-download");
				String filedisplay = list.get(0).getBalanceBillName().concat(".xls");
				filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
				response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
				ExportCostBalanceBill<BalanceBill> exportCostBalanceBill = new ExportCostBalanceBill<BalanceBill>();
				exportCostBalanceBill.exportExcel(list.get(0).getBalanceBillName(), headers, list, response.getOutputStream(), list.get(0).getTotalPayElectricCharge(), list.get(0).getSumTotalChargingKWH(), list.get(0).getTotalCostSubtotal(), list.get(0).getTotalDifference());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			map.put("result", "Success");
		}

		return map;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportPhaseSummary")
	@ResponseBody
	public Map<String, Object> exportPhaseSummary(String checkFlag, HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "阶段汇总导出");

		if (!checkFlag.isEmpty()) {
			String[] headers = {"序号", "充电站名称", "线路名称", "车队名称", "充电电量", "备注"};
			List<ReviewRecord> list = (List<ReviewRecord>) this.getSessionAttribute("searchPhaseSummary");
			ChargingRecord chargingRecord = (ChargingRecord) this.getSessionAttribute("phaseSummaryCondition");
			if(list == null || list.size() == 0) {
				map.put("result", "NotFound");
			} else {
				String name = list.get(0).getSubBranchCompanyName().concat(chargingRecord.getStartChargingDate()).concat("——").concat(chargingRecord.getEndChargingDate()).concat("充电记录汇总");
				List<Double> electrics = new ArrayList<Double>();
				double electric = 0;
				for(int i = 0; i < list.size(); i++) {
					electric = DoubleUtil.add(electric, list.get(i).getSumChargingKWH());
					if(i == list.size() - 1) {
						electrics.add(electric);
					} else if(!list.get(i).getChargingStationName().equals(list.get(i+1).getChargingStationName())) {
						electrics.add(electric);
						electric = 0;
					}
				}
				try {
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/x-download");
					String filedisplay = name.concat(".xls");
					filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
					response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
					ExportPhaseSummary<ReviewRecord> exportCostBalanceBill = new ExportPhaseSummary<ReviewRecord>();
					exportCostBalanceBill.exportExcel(name, headers, list, response.getOutputStream(), electrics);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			map.put("result", "Success");
		}
		return map;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportAllSubBranchCompanyLine")
	@ResponseBody
	public Map<String, Object> exportAllSubBranchCompanyLine(LineBalance lineBalance, String checkFlag, HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "分公司各线路明细导出");

		List<LineBalance> list = null;

		double allTotalChargingKWH = 0;
		double totalChargingPrice = 0;
		double totalServicePrice = 0;
		double totalPrice = 0;
		
		if (!checkFlag.isEmpty()) {
			String[] headers = {"序号", "日期", "充电站", "车队", "线路", "充电电量/度", "系数", "结算电量/度", "电费单价", "电费小计", "92号汽油当日油价/升", "提取服务费标准", "服务费小计", "费用合计"};
			list = (List<LineBalance>) this.getSession().getAttribute("allLineBalanceList");
			allTotalChargingKWH = (double) this.getSession().getAttribute("allTotalChargingKWH");
			totalChargingPrice = (double) this.getSession().getAttribute("totalChargingPrice");
			totalServicePrice = (double) this.getSession().getAttribute("totalServicePrice");
			totalPrice = (double) this.getSession().getAttribute("totalPrice");
			ExportAllLineBalance exportAllLineBalance = new ExportAllLineBalance();
			try {
				String filedisplay = list.get(0).getSubBranchCompanyName().concat("结算明细表").concat(".xls");
				filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
				response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
				exportAllLineBalance.exportExcel(headers, list, response.getOutputStream(), allTotalChargingKWH, totalChargingPrice, totalServicePrice, totalPrice);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			this.getSession().setAttribute("allLineBalanceList", null);
		} else {
			try {
				list = balanceService.getAllSubBranchCompanyLine(lineBalance);
				if(list.size() > 0) {
					map.put("result", "Success");
					this.getSession().setAttribute("allLineBalanceList", list);
				} else {
					map.put("result", "NotFound");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportStageSummary")
	@ResponseBody
	public Map<String, Object> exportStageSummary(String checkFlag, HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "建设期统计导出开始");

		if (!checkFlag.isEmpty()) {
			String[] headers = {"序号", "建设期", "充电电量", "电费", "服务费"};
			List<ReviewRecord> list = (List<ReviewRecord>) this.getSessionAttribute("searchStageSummary");
			if(list == null || list.size() == 0) {
				map.put("result", "NotFound");
			} else {
				String name = "建设期电量费用统计";
				try {
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/x-download");
					String filedisplay = name.concat(".xls");
					filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
					response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
					ExportStageSummary<ReviewRecord> exportCostBalanceBill = new ExportStageSummary<ReviewRecord>();
					exportCostBalanceBill.exportExcel(name, headers, list, response.getOutputStream());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			map.put("result", "Success");
		}
		return map;
	}
}